package com.ming.filter;


import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 测试
 * 1）释放可以抽取公共（META-INF/dubbo配置在公共工程）【可以】
 * 
 * 2）是否需要配置filter【需要】
 * 		方案一：针对具体
 * 			@Reference(check=false,filter={"logFilter"})
			private FileService fileService;
		方案二：针对全局
			@Activate(group = {Constants.PROVIDER, Constants.CONSUMER},order = -2000)
 * 		
 * 3）整个执行顺序是什么样的？
 * 		controller.aop开始->controller方法->filter->controller.aop结束======>filter->service.aop开始->service方法->service.aop结束
 * 
 * @author Administrator
 *
 */
// @Activate表示所有的方式都生效,否则需要在服务消费端指定拦截器
@Activate(group = {Constants.PROVIDER, Constants.CONSUMER},order = -2000)
@Slf4j
public class GlobalTraceFilter implements Filter {

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		log.info("dubbo invoke start...");
		System.out.printf("url:%s  \n methodName:%s \n",invoker.getUrl(),invocation.getMethodName());
		String traceId = invocation.getAttachment("traceId");
        if(StringUtils.isEmpty(traceId)) {
        	traceId= UUID.randomUUID().toString();
            RpcContext.getContext().setAttachment("traceId",traceId);
        }else {
        	RpcContext.getContext().setAttachment("traceId",traceId);
        }
        System.out.println(LocalDateTime.now()+"  链路id: :"+traceId);
		log.info("dubbo invoke end...");
        return invoker.invoke(invocation);
	}

}
